<?php

if ( is_owner() ) {
    soc_add_function('api', 'user_cron');
} else {
    soc_add_function('api', 'public_cron');
}

function user_cron() {
    global $config, $soc;
    switch ( $_POST['fn'] ) {
        case 'cron':

            // sitemap.json
            $sitemap_json = array();

            // sitemap.xml
            $sitemap_xml = "";

            foreach( glob($soc['dir'].'/.posts/*/*/*/*/*/index.json') as $file ) {
                $json = json_decode( file_get_contents( $file ), true );

                if ( $json['public'] === 'true' ) {
                    
                    // sitemap.json
                    $url = str_replace( $soc['dir'].'/.posts', '', $file );
                    $url = $soc['url']['scheme'].'://'.$soc['url']['host'].$url;
                    array_unshift( $sitemap_json, $url );

                    // sitemap.xml
                    $url = str_replace( 'index.json', '', $url );
                    $modified = '<lastmod>'.date( 'c', $json['updated'] ).'</lastmod>';
                    $sitemap_xml = "<url><loc>{$url}</loc>{$modified}</url>\n{$sitemap_xml}";

                }

                // Fix area
                $save = false;
                if ( !isset( $json['id'] ) ) {
                    $json['id'] = sha1( $json['url'] . time() );
                    $save = true;
                }
                if ( !isset( $json['updated'] ) ) {
                    $json['updated'] = $json['unixtime'];
                    $save = true;
                }
                if ( !isset( $json['created'] ) ) {
                    preg_match( '/(\d\d\d\d)\/(\d\d)\/(\d\d)\/(\d\d)\/(\d\d)\//', $json['url'], $m );
                    $date = strtotime( $m[1].'-'.$m[2].'-'.$m[3].' '.$m[4].':'.$m[5].':00' );
                    $json['created'] = $date;
                    unset( $json['unixtime'] );
                    $save = true;
                }
                if ( isset( $json['lastmod'] ) ) {
                    unset( $json['lastmod'] );
                    $save = true;
                }
                if ( $save ) {
                    file_put_contents( $file, json_encode($json) );
                }
            }

            // sitemap.json
            file_put_contents( $soc['dir'].'/sitemap.json', json_encode($sitemap_json) );

            // sitemap.xml
            $sitemap_xml = "<?xml version='1.0' encoding='UTF-8'?>\n<urlset xmlns='http://www.sitemaps.org/schemas/sitemap/0.9'>\n{$sitemap_xml}</urlset>\n";
            file_put_contents( $soc['dir'].'/sitemap.xml', $sitemap_xml );

            /* Выход */

            exit( json_encode( array(
                'sitemap' => 'updated',
            ) ) );

        break;
    }
}

function public_cron() {
    
}